<template>
  <div v-if="pageStatus === 1">
    <el-tabs v-model="tabType" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane v-for="item in tabList" :key="item.id" :label="item.name" :name="item.id">
        <ContentWrap>
          <!-- 搜索工作栏 -->
          <el-form ref="queryFormRef" :inline="true" :model="paramsData" class="-mb-10px" label-width="68px">
            <el-form-item label="巡检编号" prop="inspectionSn">
              <el-input v-model="paramsData.inspectionSn" class="!w-360px" clearable placeholder="请输入巡检编号" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="巡检项目" prop="projectTitle">
              <el-input v-model="paramsData.projectTitle" class="!w-360px" clearable placeholder="请输入巡检项目"
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="巡检人" prop="inspectionEmployeeName">
              <el-input v-model="paramsData.inspectionEmployeeName" class="!w-360px" clearable placeholder="请输入巡检人"
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="巡检时间" prop="inspectionTime">
              <el-date-picker
                v-model="paramsData.inspectionTime"
                class="!w-360px"
                type="datetimerange"
                placeholder="请选择施工时间"
                range-separator="~" 
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="YYYY-MM-DD HH:mm:ss"
                @change="e => paramsData.inspectionTime = [formatDateToYMDHMS(e[0]), formatDateToYMDHMS(e[1])]"
              />
            </el-form-item>
            <el-form-item label="巡检类型" prop="type">
              <el-select v-model="paramsData.type" class="!w-360px" clearable placeholder="请选择巡检类型">
                <el-option v-for="item in inspectionTypeList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="巡检状态" prop="status">
              <el-select v-model="paramsData.status" class="!w-360px" clearable placeholder="请选择巡检状态">
                <el-option v-for="item in statusList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="整改状态" prop="rectifierRes" v-if="item.id === 2">
              <el-select v-model="paramsData.rectifierRes" class="!w-360px" clearable placeholder="请选择整改状态">
                <el-option v-for="item in rectifierResList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button v-hasPermi="['wise:inspection-logs:query']" @click="handleQuery">
                <Icon class="mr-5px" icon="ep:search" />
                搜索
              </el-button>
              <el-button @click="resetQuery">
                <Icon class="mr-5px" icon="ep:refresh" />
                重置
              </el-button>
              <el-button v-hasPermi="['wise:inspection-logs:export']" :loading="exportLoading" plain type="success"
                @click="handleExport">
                <Icon class="mr-5px" icon="ep:download" />
                导出
              </el-button>
            </el-form-item>
          </el-form>
        </ContentWrap>

        <!-- 列表 -->
        <ContentWrap>
          <el-table v-loading="loading" :data="tableData" @selection-change="tableSelectionChange">
            <el-table-column type="selection" width="30" />
            <el-table-column label="巡检编号" prop="inspectionSn" align="center" :width="220">
              <template #default="scope">
                <div v-if="scope.row.inspectionSn">{{ scope.row.inspectionSn }}</div>
                <div v-else>-</div>
              </template>
            </el-table-column>
            <el-table-column label="巡检项目" prop="projectTitle" align="center" :width="160">
              <template #default="scope">
                <div v-if="scope.row.projectTitle">{{ scope.row.projectTitle }}</div>
                <div v-else>-</div>
              </template>
            </el-table-column>
            <el-table-column label="巡检人" prop="inspectionEmployeeName" align="center" />
            <el-table-column label="巡检类型" prop="type" align="center">
              <template #default="scope">
                {{ inspectionTypeList.find(item => item.value == scope.row.type)?.label }}
              </template>
            </el-table-column>
            <el-table-column label="巡检状态" prop="status" align="center">
              <template #default="scope">
                {{ statusList.find(item => item.id == scope.row.status)?.name }}
              </template>
            </el-table-column>
            <el-table-column label="巡检评分" prop="score" align="center" />
            <el-table-column label="所属部门" prop="projectDepartment" align="center" :width="140">
              <template #default="scope">
                {{ scope.row.projectDepartment ? scope.row.projectDepartment : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="巡检时间" prop="inspectionTime" align="center" :width="160">
              <template #default="scope">
                {{ scope.row.inspectionTime ? formatDate(scope.row.inspectionTime) : '' }}
              </template>
            </el-table-column>

            <el-table-column v-if="item.id === 1" label="上传时间" prop="createTime" align="center" :width="160">
              <template #default="scope">
                {{ scope.row.createTime ? formatDate(scope.row.createTime) : '' }}
              </template>
            </el-table-column>   
            <el-table-column v-if="item.id === 1" label="上传人" prop="employeeName" align="center" :width="220">
              <template #default="scope">
                <div v-if="scope.row.employeeName">
                  {{ scope.row.employeeName }} <span v-if="scope.row.employeePhone">（{{ scope.row.employeePhone }}）</span>
                </div>
                <div v-else>-</div>
              </template>
            </el-table-column> 

            <el-table-column v-if="item.id === 2" label="整改状态" prop="rectifierRes" align="center">
              <template #default="scope">
                {{ rectifierResList.find(item => item.id == scope.row.rectifierRes)?.name }}
              </template>
            </el-table-column>
            <el-table-column v-if="item.id === 2" label="时间" prop="rectifierBackstageTime" align="center" :width="240">
              <template #default="scope">
                <div>上传时间：{{ scope.row.createTime ? formatDate(scope.row.createTime) : '-' }}</div>
                <div>整改时间：{{ scope.row.rectifierBackstageTime ? formatDate(scope.row.rectifierBackstageTime) : '-' }}</div>
              </template>
            </el-table-column>   
            <el-table-column v-if="item.id === 2" label="人员" prop="rectifierBackstageEmployeeName" align="center" :width="240">
              <template #default="scope">
                <div v-if="scope.row.employeeName">
                  上传人：{{ scope.row.employeeName }} <span v-if="scope.row.employeePhone">（{{ scope.row.employeePhone }}）</span>
                </div>
                <div v-else>上传人：-</div>
                <div v-if="scope.row.rectifierBackstageEmployeeName">
                  整改人：{{ scope.row.rectifierBackstageEmployeeName }} <span v-if="scope.row.rectifierBackstageEmployeePhone">（{{ scope.row.rectifierBackstageEmployeePhone }}）</span>
                </div>
                <div v-else>整改人：-</div>
              </template>
            </el-table-column> 
            <el-table-column :width="100" align="center" label="操作" fixed="right">
              <template #default="scope">
                <el-button v-hasPermi="['wise:inspection-logs:update']" link type="primary" @click="openForm(tabType, scope.row.id)">
                  {{ tabType === 1 ? '查看' : '整改' }}
                </el-button>
              </template>
            </el-table-column>

          </el-table>


          <!-- 分页 -->
          <Pagination v-model:limit="paramsData.pageSize" v-model:page="paramsData.pageNo" :total="total" @pagination="getList" />
        </ContentWrap>
      </el-tab-pane>
    </el-tabs>
  </div>


  <SafetyForm v-else ref="safetyFormRef" />
</template>
<script setup>
  import {ref,reactive,nextTick} from "vue"
  import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
  import { formatDateToYMDHMS } from '@/utils/index'
  import { getSafetyList, exportSafety } from '@/api/viewsApi/safety'
  import { formatDate } from '@/utils/formatTime'
  import { defaultProps, handleTree } from '@/utils/tree'
  import * as DeptApi from '@/api/system/dept'
  import download from '@/utils/download'
  import SafetyForm from "./safetyForm.vue"
  const inspectionTypeList = getIntDictOptions(DICT_TYPE.INSPECTION_TYPE)
  const message = useMessage() // 消息弹窗
  const queryFormRef = ref() // 搜索的表单
  const exportLoading = ref(false) // 导出的加载中
  const pageStatus = ref(1) // 页面状态：1 - 列表页；2 - 新增编辑页
  const tabType = ref(1) // 当前选中的tab
  const tabList = [
    { name: '安全巡检', id: 1 },
    { name: '责任整改', id: 2 },
  ]
  const statusList = [
    { name: '正常', id: 0 },
    { name: '异常', id: 1 },
    { name: '责任整改', id: 2 },
  ]
  const rectifierResList = [
    { name: '待整改', id: 0 },
    { name: '整改完成', id: 1 },
    { name: '无法整改', id: 2 },
  ]
  const paramsData = reactive({
    pageNo: 1,
    pageSize: 10,
    inspectionSn: '',
    projectTitle: '',
    inspectionEmployeeName: '',
    inspectionTime: '',
    type: null,
    subType: 1,
    status: undefined,
    ids: []
  })
  const loading = ref(true) // 列表的加载中
  const total = ref(0) // 列表的总页数
  const tableData = ref([]) // 列表的数据
  const selectIds = ref([])
  const safetyFormRef = ref()


  const getList = async () => {
    loading.value = true
    try {
      const data = await getSafetyList(paramsData)
      tableData.value = data.list
      total.value = data.total
    } finally {
      loading.value = false
    }
  }
  provide('getList', getList)




  const handleClick = (tab) => {
    tabType.value = tab.props.name
    handleQuery()
  }
  
  const tableSelectionChange = (selection) => {
    selectIds.value = selection.map(item => item.id)
  }
  
  /** 搜索按钮操作 */
  const handleQuery = () => {
    paramsData.pageNo = 1
    paramsData.subType = tabType.value
    getList()
  }

  /** 重置按钮操作 */ 
  const resetQuery = () => {
    queryFormRef.value[0].resetFields()
    handleQuery()
  }

  const handleExport = async () => {
    if(selectIds.value.length > 0){
      paramsData.ids = selectIds.value
    }
    
    try {
      // 导出的二次确认
      await message.exportConfirm()
      // 发起导出
      exportLoading.value = true
      const data = await exportSafety(paramsData)
      download.excel(data, '安全巡检列表.xls')
    } catch {
    } finally {
      exportLoading.value = false
      paramsData.ids = []
    }
  }

  const openForm = (type, id) => {
    pageStatus.value = 2
    nextTick(() => {
      safetyFormRef.value.init(type, id)
    })
  }

  const deptTree = ref([]) // 部门树
  /** 获得部门树 */
  const getTree = async () => {
    deptTree.value = []
    const data = await DeptApi.getSimpleDeptList()
    deptTree.value = handleTree(data)
  }
  provide('deptTree', deptTree)

  const goBack = (type) => {
    pageStatus.value = 1
    if(type){
      getList()
    }
  }
  provide('goBack', goBack)
  
  onMounted(async() => {
    await getList()
    await getTree()
  })
</script>
<style lang="scss" scoped>

</style>
